package com.itboye.lottery.fragment;


import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.handmark.pulltorefresh.library.ObservableScrollView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.itboye.lottery.R;
import com.itboye.lottery.activity.WebActivity;
import com.itboye.lottery.activity.daletou.BascketballMainActivity;
import com.itboye.lottery.activity.daletou.DaLeTouMainActivity;
import com.itboye.lottery.activity.football.FootballMainActivity;
import com.itboye.lottery.activity.shuangseqiu.ShuangSeQiuMainActivity;
import com.itboye.lottery.adapter.HomeBottomFastTouZhuAdapter;
import com.itboye.lottery.adapter.HomeLotteryClassificationAdapter;
import com.itboye.lottery.alert.ByAlert;
import com.itboye.lottery.app.MyApplication;
import com.itboye.lottery.base.BaseFragment;
import com.itboye.lottery.bean.CodeBean;
import com.itboye.lottery.bean.IndexDataBean;
import com.itboye.lottery.bean.OrderBean;
import com.itboye.lottery.dialog.PayDialog;
import com.itboye.lottery.presenter.UserPresenter;
import com.itboye.lottery.retrofit.ResponseCallback;
import com.itboye.lottery.utils.CodeUtil;
import com.itboye.lottery.utils.Const;
import com.itboye.lottery.widget.indexfragmentbanner.BezierViewPager;
import com.itboye.lottery.widget.indexfragmentbanner.CardPagerAdapter;
import com.itboye.lottery.widget.titlebarwidget.TranslucentActionBar;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import static com.itboye.lottery.utils.SPUtils.getSp;
import static com.itboye.lottery.utils.Utils.clip;
import static in.srain.cube.views.ptr.util.PtrLocalDisplay.dp2px;


/**
 * Created by Administrator on 2017/11/10.
 */

public class HomeFragment extends BaseFragment implements ResponseCallback {


    private BezierViewPager home_banner;
    private LinearLayout indicator;
    private LinearLayout ll_lottery_classification_indicator;
    private RecyclerView vp_lottery_classification;
    private LinearLayout rl_lottery_classification;
    private RecyclerView rv_bottom_fast_touzhu;
    private TranslucentActionBar transaction_bar;
    private ViewFlipper tv_winning_message;
    private TextView tv_actionbar_right;
    private UserPresenter userPresenter;
    private HomeLotteryClassificationAdapter homeClassfyAdapter;
    private List<IndexDataBean.Fast_arr> fast_arrList;
    private HomeBottomFastTouZhuAdapter bottomAdapter;
    private IndexDataBean indexDataBean;
    TextView tv_getToken;
    PullToRefreshScrollView pull_to_refresh_scrollView;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initData() {
        initTitleBar();
        initPresenter();
        tv_getToken.setOnLongClickListener(view -> {
            clip(getSp(Const.Companion.getTOKEN()) + "");
            return true;
        });
        pull_to_refresh_scrollView.setRefreshing(true);
        pull_to_refresh_scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ObservableScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ObservableScrollView> refreshView) {
                getIndexData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ObservableScrollView> refreshView) {

            }
        });
        getIndexData();
    }




    private void getIndexData() {
        showDialog();
        userPresenter.homeIndex();
    }

    private void initPresenter() {
        userPresenter = new UserPresenter(this);
    }

    private void initFliper(List<IndexDataBean.Prize> prizeList) {
        tv_winning_message.removeAllViews();
        for (int i = 0; i < prizeList.size(); i++) {
            TextView textView = new TextView(getActivity());
            textView.setText(Html.fromHtml("恭喜[" + prizeList.get(i).getNickname() + "]投注 " + prizeList.get(i).getName() + " 中奖<font color='red'>" + prizeList.get(i).getPrize_money() + "</font>元"));
            textView.setGravity(Gravity.CENTER);
            tv_winning_message.addView(textView);
        }

    }

    private void initTitleBar() {
//        actionbarSet(transaction_bar, "首页", R.mipmap.ic_shop_click, "", 0, "", this@MainActivity)
    }

    private void initBottomClassification(List<IndexDataBean.Fast_arr> fast_arrList) {
        //构造底部分类的数据
        this.fast_arrList = fast_arrList;
        for (int i = 0; i < fast_arrList.size(); i++) {
            beginCode(i);
        }
        rv_bottom_fast_touzhu.setLayoutManager(new LinearLayoutManager(getActivity()));
        bottomAdapter = new HomeBottomFastTouZhuAdapter(this, fast_arrList);
        rv_bottom_fast_touzhu.setAdapter(bottomAdapter);
        rv_bottom_fast_touzhu.setNestedScrollingEnabled(false);
//        rv_bottom_fast_touzhu.setHasFixedSize(true);
    }

    private void beginCode(int i) {
        switch (fast_arrList.get(i).getId()) {
            case 1001://双色球 6+1
            case 1002://
                generateRandomCode(i, 6, 1);
                break;
            case 2001://大乐透 5+2
                generateRandomCode(i, 5, 2);
                break;

        }
    }

    private void initLotteryClassification(List<IndexDataBean.Caizhong> caizhongList) {
        ll_lottery_classification_indicator.removeAllViews();
        homeClassfyAdapter = new HomeLotteryClassificationAdapter(caizhongList);
        vp_lottery_classification.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        vp_lottery_classification.setAdapter(homeClassfyAdapter);
        for (IndexDataBean.Caizhong caizhong : caizhongList) {
            if (caizhong.getCode() == 1001) {
                if(caizhong.getStatus() == 0 || caizhong.getStatus() == 3)
                {
                    Const.Companion.setShuangseqiu(true);
                }else{
                    Const.Companion.setShuangseqiu(false);
                }
            }
            if (caizhong.getCode() == 2001 ) {
                if (caizhong.getStatus() == 0 || caizhong.getStatus() == 3) {
                    Const.Companion.setDaletou(true);
                }
                else{
                    Const.Companion.setDaletou(false);
                }
            }
            if (caizhong.getCode() == 3010 ) {
                if((caizhong.getStatus() == 0 || caizhong.getStatus() == 3)){
                    Const.Companion.setZq(true);
                }else{
                    Const.Companion.setZq(false);
                }
            }
            if (caizhong.getCode() == 3001 ) {
                if((caizhong.getStatus() == 0 || caizhong.getStatus() == 3)){
                    Const.Companion.setLq(true);
                }else{
                    Const.Companion.setLq(false);
                }
            }
        }
        homeClassfyAdapter.setOnItemClickListener((view, position) -> {
            int code = caizhongList.get(position).getCode();
            switch (code) {
                case 1001://双色球
                    if (Const.Companion.getShuangseqiu()) {
                        startActivity(new Intent(getActivity(), ShuangSeQiuMainActivity.class));
                    }else{
                        ByAlert.alert(view.getTag());
                    }
                    break;
                case 2001:
                    if (Const.Companion.getDaletou()) {
                        startActivity(new Intent(getActivity(), DaLeTouMainActivity.class));
                    }else{
                        ByAlert.alert(view.getTag());
                    }
                    break;
                case 3010:
                    if (Const.Companion.getZq()) {
                        startActivity(new Intent(getActivity(), FootballMainActivity.class));
                    }else{
                        ByAlert.alert(view.getTag());
                    }
                    break;
                case 3001:
                    if (Const.Companion.getLq()) {
                        startActivity(new Intent(getActivity(), BascketballMainActivity.class));
                    }else{
                        ByAlert.alert(view.getTag());
                    }
                    break;
            }
        });
    }

    private void setSelectIndicator(int position) {
        for (int i = 0; i < ll_lottery_classification_indicator.getChildCount(); i++) {
            ImageView imageView = (ImageView) ll_lottery_classification_indicator.getChildAt(i);
            if (position == i) {
                imageView.setSelected(true);
            } else {
                imageView.setSelected(false);
            }
        }
    }

    @SuppressLint("NewApi")
    private void setLotteryClassificationIndicator() {
        ImageView imageView = new ImageView(getContext());
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(20, 20);
        layoutParams.setMargins(10, 10, 10, 10);
        imageView.setLayoutParams(layoutParams);
        imageView.setBackground(getActivity().getResources().getDrawable(R.drawable.indicator_selector));
        ll_lottery_classification_indicator.addView(imageView);
    }

    @Override
    public void onClick(View view) {
        int position = 0;
        switch (view.getId()) {
            case R.id.tv_actionbar_right:
//                wxLogin();
                wxLoginBackTest();
                break;
            case R.id.tv_home_bottom_classifycation_style_1_touzhu:
                //快速投注
                position = Integer.parseInt(view.getTag().toString());
                int id = this.fast_arrList.get(position).getId();
                String num = getNumStrForColorBall(position);//双色球大乐透号码格式化
                Log.v("bet_params", num);
                switch (id) {
                    case 2001://大乐透
                        userPresenter.createOrderForDaLeTou(num, 1, "1", 1, 0, 0);
                        break;
                    case 1001://双色球
                    case 1002://双色球
                        userPresenter.createOrderForColorBall(num, 1, "1", 1, 0, 0);
                        break;
                }
                break;
            case R.id.tv_home_bottom_classifycation_style_1_refresh:
                position = Integer.valueOf(view.getTag().toString());
                beginCode(position);
                bottomAdapter.notifyDataSetChanged();
                break;
            case R.id.tv_home_bottom_classifycation_style_1_load_more:
                position = (int) view.getTag();
                if (indexDataBean.getFast_arr().get(position).getId() == 1001 || indexDataBean.getFast_arr().get(position).getId() == 1002) {
                    startActivity(new Intent(getActivity(), ShuangSeQiuMainActivity.class));
                } else if (indexDataBean.getFast_arr().get(position).getId() == 2001) {
                    startActivity(new Intent(getActivity(), DaLeTouMainActivity.class));
                }
                break;
        }
    }

    private String getNumStrForColorBall(int position) {
        ArrayList<CodeBean> codeBeanArrayList = this.fast_arrList.get(position).getArrayListCode();
        StringBuffer num = new StringBuffer();
        num.append("[\"");
        boolean isBlueFirst = true;
        for (CodeBean codeBean : codeBeanArrayList) {
            if (codeBean.getType() == 2) {
                //是蓝色球
                if (isBlueFirst) {
                    num.delete(num.length() - 1, num.length());
                    num.append("|");
                    isBlueFirst = false;
                }
            }
            num.append(codeBean.getCodeValue() + ",");
        }
        num = new StringBuffer(num.substring(0, num.length() - 1));
        num.append("\"]");
        return num.toString();
    }

    private void generateRandomCode(int position, int redNum, int blueNum) {
        ArrayList arrayListCode = new ArrayList();
        arrayListCode.addAll(CodeUtil.randomCommon(1, 33, redNum, 0));//红色球
        arrayListCode.addAll(CodeUtil.randomCommon(1, 16, blueNum, 2));//蓝色球
        fast_arrList.get(position).setArrayListCode(arrayListCode);
    }

    private void wxLoginBackTest() {
//        userPresenter.wxLogin("wx_codesjshhs");
    }

    private void setLunBoData(List<IndexDataBean.Banner> bannerList) {
        int mWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        float heightRatio = 0.56f;  //高是宽的 0.565 ,根据图片比例

        CardPagerAdapter cardAdapter = new CardPagerAdapter(getActivity());
        cardAdapter.addImgUrlList(bannerList);
//        cardAdapter.addImgUrlList(bannerList);
//        cardAdapter.addImgUrlList(bannerList);


        //设置阴影大小，即vPage  左右两个图片相距边框  maxFactor + 0.3*CornerRadius   *2
        //设置阴影大小，即vPage 上下图片相距边框  maxFactor*1.5f + 0.3*CornerRadius
        int maxFactor = mWidth / 25;
        maxFactor=0;
        cardAdapter.setMaxElevationFactor(maxFactor);
        if (bannerList.size() <= 0) {
            return;
        }
        int mWidthPading = 0;
        if (cardAdapter.getImageUrlList().size() == 1) {
            mWidthPading = dp2px(20);
        } else {
            mWidthPading = mWidth / 8;
        }

        //因为我们adapter里的cardView CornerRadius已经写死为10dp，所以0.3*CornerRadius=3
        //设置Elevation之后，控件宽度要减去 (maxFactor + dp2px(3)) * heightRatio
        //heightMore 设置Elevation之后，控件高度 比  控件宽度* heightRatio  多出的部分
        float heightMore = (1.5f * maxFactor + dp2px(3)) - (maxFactor + dp2px(3)) * heightRatio;
        int mHeightPading = (int) (mWidthPading * heightRatio - heightMore);

        home_banner.setLayoutParams(new LinearLayout.LayoutParams(mWidth, (int) (mWidth * heightRatio)));
        home_banner.setPadding(6, 6, 6, 6);
//        home_banner.setClipToPadding(false);
        home_banner.setLoopEnable(true);
        home_banner.setDurating(3000);
        home_banner.setAdapter(cardAdapter);
//        home_banner.showTransformer(0.2f);
        home_banner.setIndicatorView(indicator);
        home_banner.startLoop();
        cardAdapter.setOnCardItemClickListener(position -> {
            if (TextUtils.isEmpty(cardAdapter.getImageUrlList().get(position).getLink())) {
                return;
            }
            if (!cardAdapter.getImageUrlList().get(position).getLink().startsWith("http")) {
                return;
            }
            startActivity(new Intent(getActivity(), WebActivity.class).putExtra("title", "").putExtra("url", cardAdapter.getImageUrlList().get(position).getLink()));
        });
    }

    @Override
    public void success(@NotNull Object o, @NotNull String requestSuccessType) {
        dissDialog();
        pull_to_refresh_scrollView.onRefreshComplete();
        if (requestSuccessType == userPresenter.homeIndex_SUCCESS) {
            indexDataBean = (IndexDataBean) o;
            setLunBoData(indexDataBean.getBanner());//加载轮播
            initLotteryClassification(indexDataBean.getCaizhong());//加载彩种分类
            initFliper(indexDataBean.getPrize());//垂直滚动轮播
            initBottomClassification(indexDataBean.getFast_arr());
        } else if (requestSuccessType == userPresenter.createOrderForColorBall_SUCCESS || requestSuccessType == userPresenter.createOrderForDaLeTou_SUCCESS) {
            OrderBean orderBean = (OrderBean) o;
            PayDialog payDialog = new PayDialog(getActivity(), true);
            payDialog.setOrderBean(orderBean);
            payDialog.show();
        }
    }

    @Override
    public void fail(int code, @NotNull Object msg, @NotNull String requestErrorType) {
        dissDialog();
        pull_to_refresh_scrollView.onRefreshComplete();
        ByAlert.alert(msg);
    }
}
